﻿using System.Linq;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;

namespace Gp.Scripts.Editor
{
    public static class EditorCommonUtils
    {
        public static void CreateObjectInScene(GameObject newGameObject, bool autoSelect = true)
        {
            Transform camTrans = SceneView.GetAllSceneCameras().First().transform;
            Ray ray = new Ray(camTrans.position, camTrans.TransformDirection(Vector3.forward));
            if (Physics.Raycast(ray, out var hit))
            {
                newGameObject.transform.position = hit.point;
            }

            if (!Application.isPlaying) EditorSceneManager.MarkSceneDirty(newGameObject.scene);
            if (autoSelect) Selection.activeGameObject = newGameObject;
        }


        public static Transform GetSceneCameraTransform(this ITopToolbarDrawer self) =>
            SceneView.GetAllSceneCameras().First().transform;


        public static void SmartDestroy<T>(GameObject go) where T : Object
        {
            SmartDestroy(go.GetComponent<T>());
        }


        public static void SmartDestroy(Object obj)
        {
            if (obj == null) return;
            if (!Application.isPlaying)
            {
                Object.DestroyImmediate(obj);
            }
            else Object.Destroy(obj);
        }
    }
}